package com.api.shopapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.common.RedisHashUtil;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.BusinessDTO;
import com.api.shopapi.entity.dto.ElderlyViewsDTO;
import com.api.shopapi.entity.views.MonthAdd;
import com.api.shopapi.entity.views.ViewsHome;
import com.api.shopapi.entity.views.VisualAccount;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.info.ProjectInfoProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.*;

@RestController
@RequestMapping("Views")
public class ViewsController extends BaseController{


    @Autowired
    @Qualifier("ViewsServiceImplOne")
    private ViewsService viewsService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("ElderlyClassServiceImplOne")
    private ElderlyClassService elderlyClassService;

    @Autowired
    @Qualifier("ElderlyServiceImplOne")
    private ElderlyService elderlyService;

    @Autowired
    @Qualifier("OrderBusinessServiceImplOne")
    private OrderBusinessService orderBusinessService;

    @Autowired
    @Qualifier("BusinessServiceImplOne")
    private BusinessService businessService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;

    @Autowired
    @Qualifier("GovernmentServiceImplOne")
    private GovernmentService governmentService;

    @Autowired
    @Qualifier("VisualAccountServiceImplOne")
    private VisualAccountService visualAccountService;

    @Autowired
    protected RedisHashUtil<String> redisHashUtil;

    @RequestMapping(value = "GetElderlyList", method = RequestMethod.POST)
    public MyResult GetElderlyList(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Views/GetElderlyList");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            List<String> governmentCodeListStr=new ArrayList<>();
            for(int i=0;i<governmentCodeList.size();i++){
                governmentCodeListStr.add(governmentCodeList.getString(i));
            }
            PageInfo<ElderlyViewsDTO> elderlyDTOPageInfo = viewsService.getList(pageIndex, pageSize,governmentCodeListStr);
            return success(elderlyDTOPageInfo);
        } catch (Exception e) {
            insertError("/Views/GetElderlyList", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "HomeData", method = RequestMethod.POST)
    public MyResult HomeData(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Views/HomeData");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            ViewsHome viewsHome = new ViewsHome();
            for (int i=0;i<governmentCodeList.size();i++){
                String key="ShopHomePageData"+governmentCodeList.get(i);
                if(redisHashUtil.isKeyExists(key)){
                    String jsonObject1 = redisHashUtil.get(key);
                    JSONObject jsonObject2 = JSON.parseObject(jsonObject1);
                    ViewsHome viewsHome1 =jsonObject2.getObject("viewsHome",ViewsHome.class);
                    viewsHome.setAccept(viewsHome.getAccept()+viewsHome1.getAccept());
                    viewsHome.setBuild(viewsHome.getBuild()+viewsHome1.getBuild());
                    viewsHome.setBusiness(viewsHome.getBusiness()+viewsHome1.getBusiness());
                    viewsHome.setGovernment(viewsHome.getGovernment()+viewsHome1.getGovernment());
                    viewsHome.setServe(viewsHome.getServe()+viewsHome1.getServe());
                    viewsHome.setServiceObject(viewsHome.getServiceObject()+viewsHome1.getServiceObject());
                    viewsHome.setServicePeople(viewsHome.getServicePeople()+viewsHome1.getServicePeople());
                    viewsHome.setSuccess(viewsHome.getSuccess()+viewsHome1.getSuccess());
                }
            }
            return success(viewsHome);
        } catch (Exception e) {
            insertError("/Views/HomeData", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //
    @RequestMapping(value = "NewInsertElderly", method = RequestMethod.POST)
    public MyResult NewInsertElderly(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Views/NewInsertElderly");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            return success(getElderlyData("NewInsertElderlyData",governmentCodeList));
        } catch (Exception e) {
            insertError("/Views/NewInsertElderly", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //
    @RequestMapping(value = "NowElderly", method = RequestMethod.POST)
    public MyResult NowElderly(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Views/NowElderly");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            return success(getElderlyData("NowElderlyData",governmentCodeList));
        } catch (Exception e) {
            insertError("/Views/NowElderly", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //
    @RequestMapping(value = "TotalElderly", method = RequestMethod.POST)
    public MyResult TotalElderly(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Views/NowElderly");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            return success(getElderlyData("TotalElderlyData",governmentCodeList));
        } catch (Exception e) {
            insertError("/Views/NowElderly", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //
    @RequestMapping(value = "OrderCount", method = RequestMethod.POST)
    public MyResult OrderCount(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Views/OrderCount");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            int nowYearOrder = 0;
            int lastYearOrder = 0;
            int nowMonthsOrder = 0;
            int lastMonthsOrder = 0;
            for (int i=0;i<governmentCodeList.size();i++){
                String key="OrderCountData"+governmentCodeList.get(i);
                if(redisHashUtil.isKeyExists(key)){
                    String jsonObject1 = redisHashUtil.get(key);
                    JSONObject jsonObject2 = JSON.parseObject(jsonObject1);
                    nowYearOrder+= jsonObject2.getIntValue("nowYearOrder");
                    lastYearOrder+= jsonObject2.getIntValue("lastYearOrder");
                    nowMonthsOrder+= jsonObject2.getIntValue("nowMonthsOrder");
                    lastMonthsOrder+= jsonObject2.getIntValue("lastMonthsOrder");
                }
            }
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("nowYearOrder", nowYearOrder);
            jsonObject1.put("lastYearOrder", lastYearOrder);
            jsonObject1.put("nowMonthsOrder", nowMonthsOrder);
            jsonObject1.put("lastMonthsOrder",lastMonthsOrder);
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Views/OrderCount", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //
    @RequestMapping(value = "OrderPrice", method = RequestMethod.POST)
    public MyResult OrderPrice(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Views/OrderPrice");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            int nowYearMoney = 0;
            int lastYearMoney = 0;
            int nowMonthsMoney = 0;
            int lastMonthsMoney = 0;
            for (int i=0;i<governmentCodeList.size();i++){
                String key="OrderPriceData"+governmentCodeList.get(i);
                if(redisHashUtil.isKeyExists(key)){
                    String jsonObject1 = redisHashUtil.get(key);
                    JSONObject jsonObject2 = JSON.parseObject(jsonObject1);
                    nowYearMoney+= jsonObject2.getIntValue("nowYearMoney");
                    lastYearMoney+= jsonObject2.getIntValue("lastYearMoney");
                    nowMonthsMoney+= jsonObject2.getIntValue("nowMonthsMoney");
                    lastMonthsMoney+= jsonObject2.getIntValue("lastMonthsMoney");
                }
            }
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("nowYearMoney", nowYearMoney);
            jsonObject1.put("lastYearMoney", lastYearMoney);
            jsonObject1.put("nowMonthsMoney", nowMonthsMoney);
            jsonObject1.put("lastMonthsMoney",lastMonthsMoney);
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Views/OrderPrice", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    private JSONObject getElderlyData(String keys,JSONArray governmentCodeList){
        int total=0;
        int man=0;
        int woman=0;
        List<JSONObject> elderClassList=new ArrayList<>();
        for (int i=0;i<governmentCodeList.size();i++){
            String key=keys+governmentCodeList.get(i);
            if(redisHashUtil.isKeyExists(key)){
                String jsonObject1 = redisHashUtil.get(key);
                JSONObject jsonObject2 = JSON.parseObject(jsonObject1);
                total += jsonObject2.getIntValue("total");
                man += jsonObject2.getIntValue("man");
                woman += jsonObject2.getIntValue("woman");
                JSONArray elderClassList1 = jsonObject2.getJSONArray("elderClassList");
                for(int j=0;j<elderClassList1.size();j++){
                    JSONObject jsonObject3 = elderClassList1.getJSONObject(j);
                    int index=0;
                    for (JSONObject o:elderClassList){
                        String elderlyClassName = o.getString("elderlyClassName");
                        if(jsonObject3.getString("elderlyClassName").equals(elderlyClassName)){
                            int elderlyCount = o.getIntValue("elderlyCount");
                            elderlyCount+=jsonObject3.getIntValue("elderlyCount");
                            o.put("elderlyCount",elderlyCount);
                            index=1;
                            break;
                        }
                    }
                    if(index==0){
                        elderClassList.add(jsonObject3);
                    }
                }
            }
        }
        JSONObject jsonObject1=new JSONObject();
        jsonObject1.put("total", total);
        jsonObject1.put("man", man);
        jsonObject1.put("woman", woman);
        jsonObject1.put("elderClassList",elderClassList);
        return jsonObject1;
    }

    //首页展示人员数量
    @RequestMapping(value = "GetElderlyCount", method = RequestMethod.POST)
    public MyResult GetElderlyCount(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Views/GetElderlyCount");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);
            String key="NowElderlyData"+staff.getGovernmentCode();
            if(redisHashUtil.isKeyExists(key)) {
                String s = redisHashUtil.get(key);
                JSONObject jsonObject2 = JSON.parseObject(s);
                return success(jsonObject2);
            }
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("total", 0);
            jsonObject1.put("man", 0);
            jsonObject1.put("woman", 0);
            List<JSONObject> elderClassList=new ArrayList<>();
            jsonObject1.put("elderClassList",elderClassList);
            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Views/GetElderlyCount",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //首页展示订单数量
    @RequestMapping(value = "GetOrderCount", method = RequestMethod.POST)
    public MyResult GetOrderCount(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Views/GetOrderCount");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);
            String key="OrderCountData"+staff.getGovernmentCode();
            if(redisHashUtil.isKeyExists(key)) {
                String s = redisHashUtil.get(key);
                JSONObject jsonObject2 = JSON.parseObject(s);
                return success(jsonObject2);
            }
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("nowYearOrder", 0);
            jsonObject1.put("lastYearOrder", 0);
            jsonObject1.put("nowMonthsOrder", 0);
            jsonObject1.put("lastMonthsOrder", 0);

            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Views/GetOrderCount",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //首页展示订单金额
    @RequestMapping(value = "GetOrderPrice", method = RequestMethod.POST)
    public MyResult GetOrderPrice(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Views/GetOrderPrice");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);


            Double nowYearMoney = orderBusinessService.getMoneyNowYearMoney(staff.getGovernmentCode());
            if (nowYearMoney == null) {
                nowYearMoney = 0.00;
            }
            Double lastYearMoney = orderBusinessService.getMoneyLastYearMoney(staff.getGovernmentCode());
            if (lastYearMoney == null) {
                lastYearMoney = 0.00;
            }
            Double nowMonthsMoney = orderBusinessService.getMoneyNowMonthsMoney(staff.getGovernmentCode());
            if (nowMonthsMoney == null) {
                nowMonthsMoney = 0.00;
            }
            Double lastMonthsMoney = orderBusinessService.getMoneyLastMonthsMoney(staff.getGovernmentCode());
            if (lastMonthsMoney == null) {
                lastMonthsMoney = 0.00;
            }
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("nowYearMoney", nowYearMoney);
            jsonObject1.put("lastYearMoney", lastYearMoney);
            jsonObject1.put("nowMonthsMoney", nowMonthsMoney);
            jsonObject1.put("lastMonthsMoney", lastMonthsMoney);

            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Views/GetOrderPrice",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //可视化首页定时缓存接口
    @Scheduled(cron = "0 0 1 * * ? ")
    @RequestMapping(value = "HomeDataScheduled", method = RequestMethod.GET)
    public String HomePageDataScheduled(){
        try {
            List<Government> governmentCodelist = governmentService.getList();            //查询所有的政府机构名称
            for (Government governments : governmentCodelist) {
                String governmentCode = governments.getGovernmentCode();
                String key = "ShopHomePageData" + governmentCode;
                int serviceObject = viewsService.getTotalServiceObjectNew(governmentCode);
                int business = viewsService.getTotalBusinessNew(governmentCode);
                int servicePeople = viewsService.getTotalServicePeopleNew(governmentCode);
                int build = viewsService.getTotalBuildNew(governmentCode);
                int accept = viewsService.getTotalAcceptNew(governmentCode);
                int serve = viewsService.getTotalServeNew(governmentCode);
                int success = viewsService.getTotalSuccessNew(governmentCode);
                ViewsHome viewsHome = new ViewsHome();
                viewsHome.setServiceObject(serviceObject);
                viewsHome.setServicePeople(servicePeople);
                viewsHome.setBusiness(business);
                viewsHome.setBuild(build);
                viewsHome.setAccept(accept);
                viewsHome.setServe(serve);
                viewsHome.setSuccess(success);
                viewsHome.setGovernment(1);
                JSONObject jsonObject1 =new JSONObject();
                jsonObject1.put("viewsHome",viewsHome);
                redisHashUtil.put(key,jsonObject1.toString(),-1);
            }
            return "success";
        } catch (Exception e) {
            insertError("/Views/HomePageDataScheduled","getHomePageData", getExceptionMsg(e), "api");
            return "fail";
        }
    }

    //可视化本月新增服务对象数定时缓存接口
    @Scheduled(cron = "0 0 1 * * ? ")
    @RequestMapping(value = "NewInsertElderlyScheduled", method = RequestMethod.GET)
    public String NewInsertElderlyScheduled(){
        try {
            List<Government> governmentCodelist = governmentService.getList();            //查询所有的政府机构名称
            for (Government governments : governmentCodelist) {
                String governmentCode = governments.getGovernmentCode();
                String key = "NewInsertElderlyData" + governmentCode;
                ShopPageData shopPageData = viewsService.getElderlyByNew(governmentCode);
                JSONObject jsonObject1=new JSONObject();
                jsonObject1.put("total", shopPageData.getTotal());
                jsonObject1.put("man", shopPageData.getMan());
                jsonObject1.put("woman", shopPageData.getWoman());

                List<JSONObject> elderClassList=new ArrayList<>();

                List<ElderlyClass> elderlyClassList = elderlyClassService.getList(governmentCode);
                for (ElderlyClass elderlyClass : elderlyClassList) {
                    int count = elderlyService.getElderlyClassCountByNew(elderlyClass.getValue(), governmentCode);
                    JSONObject jsonObject2=new JSONObject();
                    jsonObject2.put("elderlyClassName",elderlyClass.getName());
                    jsonObject2.put("elderlyCount",count);
                    elderClassList.add(jsonObject2);
                }
                jsonObject1.put("elderClassList",elderClassList);
                redisHashUtil.put(key,jsonObject1.toString(),-1);
            }
            return "success";
        } catch (Exception e) {
            insertError("/Views/NewInsertElderlyScheduled","getHomePageData", getExceptionMsg(e), "api");
            return "fail";
        }
    }

    //可视化现有服务对象数定时缓存接口
    @Scheduled(cron = "0 0 1 * * ? ")
    @RequestMapping(value = "NowElderlyScheduled", method = RequestMethod.GET)
    public String NowElderlyScheduled(){
        try {
            List<Government> governmentCodelist = governmentService.getList();            //查询所有的政府机构名称
            for (Government governments : governmentCodelist) {
                String governmentCode = governments.getGovernmentCode();
                String key = "NowElderlyData" + governmentCode;
                ShopPageData shopPageData = viewsService.getElderly(governmentCode);
                JSONObject jsonObject1=new JSONObject();
                jsonObject1.put("total", shopPageData.getTotal());
                jsonObject1.put("man", shopPageData.getMan());
                jsonObject1.put("woman", shopPageData.getWoman());

                List<JSONObject> elderClassList=new ArrayList<>();

                List<ElderlyClass> elderlyClassList = elderlyClassService.getList(governmentCode);
                for (ElderlyClass elderlyClass : elderlyClassList) {
                    int count = elderlyService.getElderlyClassCount(elderlyClass.getValue(), governmentCode);
                    JSONObject jsonObject2=new JSONObject();
                    jsonObject2.put("elderlyClassName",elderlyClass.getName());
                    jsonObject2.put("elderlyCount",count);
                    elderClassList.add(jsonObject2);
                }
                jsonObject1.put("elderClassList",elderClassList);
                redisHashUtil.put(key,jsonObject1.toString(),-1);
            }
            return "success";
        } catch (Exception e) {
            insertError("/Views/NowElderlyScheduled","getHomePageData", getExceptionMsg(e), "api");
            return "fail";
        }
    }

    //可视化现有服务对象数定时缓存接口
    @Scheduled(cron = "0 0 1 * * ? ")
    @RequestMapping(value = "TotalElderlyScheduled", method = RequestMethod.GET)
    public String TotalElderlyScheduled(){
        try {
            List<Government> governmentCodelist = governmentService.getList();            //查询所有的政府机构名称
            for (Government governments : governmentCodelist) {
                String governmentCode = governments.getGovernmentCode();
                String key = "TotalElderlyData" + governmentCode;
                ShopPageData shopPageData = viewsService.getElderlyTotal(governmentCode);
                JSONObject jsonObject1=new JSONObject();
                jsonObject1.put("total", shopPageData.getTotal());
                jsonObject1.put("man", shopPageData.getMan());
                jsonObject1.put("woman", shopPageData.getWoman());

                List<JSONObject> elderClassList=new ArrayList<>();

                List<ElderlyClass> elderlyClassList = elderlyClassService.getList(governmentCode);
                for (ElderlyClass elderlyClass : elderlyClassList) {
                    int count = elderlyService.getElderlyClassCountTotal(elderlyClass.getValue(), governmentCode);
                    JSONObject jsonObject2=new JSONObject();
                    jsonObject2.put("elderlyClassName",elderlyClass.getName());
                    jsonObject2.put("elderlyCount",count);
                    elderClassList.add(jsonObject2);
                }
                jsonObject1.put("elderClassList",elderClassList);
                redisHashUtil.put(key,jsonObject1.toString(),-1);
            }
            return "success";
        } catch (Exception e) {
            insertError("/Views/TotalElderlyScheduled","getHomePageData", getExceptionMsg(e), "api");
            return "fail";
        }
    }


    //可视化累计订单数定时缓存接口
    @Scheduled(cron = "0 0 1 * * ? ")
    @RequestMapping(value = "OrderCountScheduled", method = RequestMethod.GET)
    public String OrderCountScheduled(){
        try {
            List<Government> governmentCodelist = governmentService.getList();            //查询所有的政府机构名称
            for (Government governments : governmentCodelist) {
                String governmentCode = governments.getGovernmentCode();
                String key = "OrderCountData" + governmentCode;
                int nowYearOrder = orderBusinessService.getOrderNowYearOrderNew(governmentCode).size();
                int lastYearOrder = orderBusinessService.getOrderLastYearOrderNew(governmentCode).size();
                int nowMonthsOrder = orderBusinessService.getOrderNowMonthsOrderNew(governmentCode).size();
                int lastMonthsOrder = orderBusinessService.getOrderLastMonthsOrderNew(governmentCode).size();

                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("nowYearOrder", nowYearOrder);
                jsonObject1.put("lastYearOrder", lastYearOrder);
                jsonObject1.put("nowMonthsOrder", nowMonthsOrder);
                jsonObject1.put("lastMonthsOrder", lastMonthsOrder);
                redisHashUtil.put(key,jsonObject1.toString(),-1);
            }
            return "success";
        } catch (Exception e) {
            insertError("/Views/OrderCountScheduled","getHomePageData", getExceptionMsg(e), "api");
            return "fail";
        }
    }


    //可视化累计订单数定时缓存接口
    @Scheduled(cron = "0 0 1 * * ? ")
    @RequestMapping(value = "OrderPriceScheduled", method = RequestMethod.GET)
    public String OrderPriceScheduled(){
        try {
            List<Government> governmentCodelist = governmentService.getList();            //查询所有的政府机构名称
            for (Government governments : governmentCodelist) {
                String governmentCode = governments.getGovernmentCode();
                String key = "OrderPriceData" + governmentCode;
                Double nowYearMoney = orderBusinessService.getMoneyNowYearMoney(governmentCode);
                if (nowYearMoney == null) {
                    nowYearMoney = 0.00;
                }
                Double lastYearMoney = orderBusinessService.getMoneyLastYearMoney(governmentCode);
                if (lastYearMoney == null) {
                    lastYearMoney = 0.00;
                }
                Double nowMonthsMoney = orderBusinessService.getMoneyNowMonthsMoney(governmentCode);
                if (nowMonthsMoney == null) {
                    nowMonthsMoney = 0.00;
                }
                Double lastMonthsMoney = orderBusinessService.getMoneyLastMonthsMoney(governmentCode);
                if (lastMonthsMoney == null) {
                    lastMonthsMoney = 0.00;
                }
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("nowYearMoney", nowYearMoney);
                jsonObject1.put("lastYearMoney", lastYearMoney);
                jsonObject1.put("nowMonthsMoney", nowMonthsMoney);
                jsonObject1.put("lastMonthsMoney", lastMonthsMoney);
                redisHashUtil.put(key,jsonObject1.toString(),-1);
            }
            return "success";
        } catch (Exception e) {
            insertError("/Views/OrderPriceScheduled","getHomePageData", getExceptionMsg(e), "api");
            return "fail";
        }
    }



    //首页展示政府商家订单金额
    @RequestMapping(value = "GetBusinessOrderPrice", method = RequestMethod.POST)
    public MyResult GetBusinessOrderPrice(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/Views/GetBusinessOrderPrice");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);


            Double nowYearMoney = orderBusinessService.getMoneyNowYearMoney(staff.getGovernmentCode());
            if (nowYearMoney == null) {
                nowYearMoney = 0.00;
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("nowYearMoney", nowYearMoney);

            List<JSONObject> businessInfoList=new ArrayList<>();
            List<BusinessDTO> businessList = businessService.getListBusinessDTOByGovernmentCode(staff.getGovernmentCode());
            for (BusinessDTO business : businessList) {
                Double businessNowYearMoney = orderBusinessService.getBusinessNowYearMoney(business.getBusinessCode());
                if (businessNowYearMoney == null) {
                    businessNowYearMoney = 0.00;
                }
                JSONObject jsonObject2=new JSONObject();
                User user = userService.getByUserCode(business.getUserCode());
                jsonObject2.put("businessName",user.getName());
                jsonObject2.put("orderPrice",businessNowYearMoney);
                businessInfoList.add(jsonObject2);
            }
            jsonObject1.put("businessInfoList",businessInfoList);
            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Views/GetBusinessOrderPrice",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }





    //政府监管平台展示政府用户数量
    @RequestMapping(value = "ElderlyCountToGovPlatform", method = RequestMethod.POST)
    public MyResult ElderlyCountToGovPlatform(@RequestBody JSONObject jsonObject) {

        try {
            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            JSONObject jsonObject1=new JSONObject();
            int totalCount=0;
            List<JSONObject> governmentInfoList=new ArrayList<>();
            for (Object o : governmentCodeList) {
                Government government = governmentService.getByGovernmentCode(o.toString());
                int elderlyCount = viewsService.getElderlyCount(government.getGovernmentCode());
                totalCount+=elderlyCount;
                JSONObject jsonObject2=new JSONObject();
                jsonObject2.put("governmentName",government.getName());
                jsonObject2.put("elderlyCount",elderlyCount);
                governmentInfoList.add(jsonObject2);
            }
            jsonObject1.put("totalCount",totalCount);
            jsonObject1.put("governmentInfoList",governmentInfoList);

            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Views/ElderlyCountToGovPlatform",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }



    //政府监管平台展示政府本年度总订单数量
    @RequestMapping(value = "OrderCountToGovPlatform", method = RequestMethod.POST)
    public MyResult OrderCountToGovPlatform(@RequestBody JSONObject jsonObject) {

        try {

            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            JSONObject jsonObject1=new JSONObject();
            int totalCount=0;
            List<JSONObject> governmentInfoList=new ArrayList<>();
            for (Object o : governmentCodeList) {
                Government government = governmentService.getByGovernmentCode(o.toString());
                int orderCount = viewsService.getGovernmentOrderCount(government.getGovernmentCode());
                totalCount+=orderCount;
                JSONObject jsonObject2=new JSONObject();
                jsonObject2.put("governmentName",government.getName());
                jsonObject2.put("orderCount",orderCount);
                governmentInfoList.add(jsonObject2);
                governmentInfoList.add(jsonObject2);
            }
            jsonObject1.put("totalCount",totalCount);
            jsonObject1.put("governmentInfoList",governmentInfoList);

            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Views/OrderCountToGovPlatform",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //政府监管平台展示政府本年度总订单金额数量
    @RequestMapping(value = "OrderPriceToGovPlatform", method = RequestMethod.POST)
    public MyResult OrderPriceToGovPlatform(@RequestBody JSONObject jsonObject) {

        try {
            JSONArray governmentCodeList = jsonObject.getJSONArray("governmentCodeList");
            JSONObject jsonObject1=new JSONObject();
            Double totalCount=0.00;
            List<JSONObject> governmentInfoList=new ArrayList<>();
            for (Object o : governmentCodeList) {
                Government government = governmentService.getByGovernmentCode(o.toString());
                Double orderPrice = orderBusinessService.getMoneyNowYearMoney(government.getGovernmentCode());
                if(orderPrice == null){orderPrice = 0.0;}
                totalCount+=orderPrice;
                JSONObject jsonObject2=new JSONObject();
                jsonObject2.put("governmentName",government.getName());
                jsonObject2.put("orderPrice",orderPrice);
                governmentInfoList.add(jsonObject2);
            }
            jsonObject1.put("totalCount",totalCount);
            jsonObject1.put("governmentInfoList",governmentInfoList);

            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Views/OrderPriceToGovPlatform",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }


    // 获得本月第一天0点时间
    public static Date getTimesMonthmorning() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        return cal.getTime();
    }

    // 获得本月最后一天24点时间
    public static Date getTimesMonthNight() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.HOUR_OF_DAY, 24);
        return cal.getTime();
    }

    // 获取本月的开始时间
    public static Date getBeginDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);
        return getDayStartTime(calendar.getTime());
    }

    // 获取本月的结束时间
    public static Date getEndDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);
        int day = calendar.getActualMaximum(5);
        calendar.set(getNowYear(), getNowMonth() - 1, day);
        return getDayEndTime(calendar.getTime());
    }

    // 获取去年的开始时间
    public static Date getBeginDayOfLastYear() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, getNowYear() - 1);
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        cal.set(Calendar.DATE, 1);
        return getDayStartTime(cal.getTime());
    }

    // 获取去年的结束时间
    public static Date getEndDayOfLastYear() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, getNowYear() - 1);
        cal.set(Calendar.MONTH, Calendar.DECEMBER);
        cal.set(Calendar.DATE, 31);
        return getDayStartTime(cal.getTime());
    }

    // 获取上月的开始时间
    public static Date getBeginDayOfLastMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 2, 1);
        return getDayStartTime(calendar.getTime());
    }

    // 获取上月的结束时间
    public static Date getEndDayOfLastMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 2, 1);
        int day = calendar.getActualMaximum(5);
        calendar.set(getNowYear(), getNowMonth() - 2, day);
        return getDayEndTime(calendar.getTime());
    }

    // 获取本月是哪一月
    public static int getNowMonth() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return gc.get(2) + 1;
    }

    // 获取某个日期的结束时间
    public static Timestamp getDayEndTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d)
            calendar.setTime(d);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return new Timestamp(calendar.getTimeInMillis());
    }

    // 获取本年的开始时间
    public static Date getBeginDayOfYear() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, getNowYear());
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        cal.set(Calendar.DATE, 1);
        return getDayStartTime(cal.getTime());
    }

    public static Integer getNowYear() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return Integer.valueOf(gc.get(1));
    }

    public static Timestamp getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d)
            calendar.setTime(d);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return new Timestamp(calendar.getTimeInMillis());
    }


//  居家养老平台的每月新增服务对象
    @RequestMapping(value = "HomeDataCareNew", method = RequestMethod.POST)
    public MyResult HomeCareNew(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String governmentCode = jsonObject.getString("GovernmentCode");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Views/HomeDataCareNew");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            MonthAdd monthAdd = null;
            String key="getHomePageCareNew"+governmentCode;
            if(!redisHashUtil.isKeyExists(key)){
                monthAdd = new MonthAdd();
                monthAdd.setWoman(0);
                monthAdd.setMan(0);
                monthAdd.setTotal(0);
                monthAdd.setClassOne(0);
                monthAdd.setClassTwo(0);
                monthAdd.setClassThree(0);
            }else {
                String jsonObject1 = redisHashUtil.get(key);
                JSONObject jsonObject2 =JSON.parseObject(jsonObject1);
                monthAdd =jsonObject2.getObject("monthAdd",MonthAdd.class);
            }
            if(monthAdd==null){
                monthAdd = new MonthAdd();
                monthAdd.setWoman(0);
                monthAdd.setMan(0);
                monthAdd.setTotal(0);
                monthAdd.setClassOne(0);
                monthAdd.setClassTwo(0);
                monthAdd.setClassThree(0);
            }
            return success(monthAdd);
        } catch (Exception e) {
            insertError("/Views/HomeDataCareNew", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

//      本月新增的对象数
    @Scheduled(cron = "0 0 1 * * ? ")
    @RequestMapping(value = "HomePageCareNew", method = RequestMethod.GET)
    public void getHomePageCareNew() {
        List<VisualAccount> governmentCodelist = visualAccountService.getList();
        for (VisualAccount visualAccount : governmentCodelist) {
            String governmentCode = visualAccount.getGovernmentCode();
            String key = "getHomePageCareNew" + governmentCode;
            int Woman = 0;
            int Man = 0;
            int Total = 0;
            int ClassOne = 0;
            int ClassTwo = 0;
            int ClassThree = 0;
            int Woman1 = viewsService.getWomanService(governmentCode);
            int Man1 = viewsService.getManServic(governmentCode);
            int total = viewsService.getTotalServiceNews(governmentCode);
            int ClassOne1 = viewsService.getClassOneNews(governmentCode);
            int ClassTwo1 = viewsService.getClassTwoNews(governmentCode);
            int ClassThree1 = viewsService.getClassThreeNews(governmentCode);

            Woman = Woman1 + Woman;
            Man = Man1 + Man;
            Total = total + Total;
            ClassOne = ClassOne1 + ClassOne;
            ClassTwo = ClassTwo1 + ClassTwo;
            ClassThree = ClassThree1 + ClassThree;

            MonthAdd monthAdd = new MonthAdd();
            monthAdd.setWoman(Woman);
            monthAdd.setMan(Man);
            monthAdd.setTotal(Total);
            monthAdd.setClassOne(ClassOne);
            monthAdd.setClassTwo(ClassTwo);
            monthAdd.setClassThree(ClassThree);

            JSONObject jsonObject1 =new JSONObject();
            jsonObject1.put("monthAdd",monthAdd);
            redisHashUtil.put(key,jsonObject1.toString(),-1);
        }
    }
}
